<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
    width="40%"
    align-center
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="12">
          <ElFormItem label="用户名" prop="username">
            <ElInput v-model="formData.username" placeholder="请输入用户名" clearable />
          </ElFormItem>
        </el-col>
        <el-col :span="12" v-if="type === 'add'">
          <ElFormItem label="用户密码" prop="password">
            <ElInput
              v-model="formData.password"
              placeholder="初始化密码a123456"
              clearable
              show-password
            />
          </ElFormItem>
        </el-col>
        <el-col :span="12">
          <ElFormItem label="手机号" prop="phone">
            <ElInput v-model="formData.phone" placeholder="请输入手机号" clearable />
          </ElFormItem>
        </el-col>
        <el-col :span="12">
          <ElFormItem label="角色">
            <ElSelect
              v-model="formData.roleIds"
              multiple
              clearable
              placeholder="请选择角色"
              filterable
            >
              <ElOption
                v-for="role in roleList"
                :key="role.id"
                :value="role.id"
                :label="role.name"
              />
            </ElSelect>
          </ElFormItem>
        </el-col>
        <el-col :span="12">
          <ElFormItem label="邮箱">
            <ElInput v-model="formData.email" placeholder="请输入邮箱" clearable />
          </ElFormItem>
        </el-col>
        <el-col :span="12">
          <ElFormItem label="昵称">
            <ElInput
              show-word-limit
              maxlength="8"
              v-model="formData.nickname"
              placeholder="请输入昵称"
              clearable
            />
          </ElFormItem>
        </el-col>
        <el-col :span="12">
          <ElFormItem label="qq">
            <ElInput v-model="formData.qq" placeholder="请输入qq" clearable />
          </ElFormItem>
        </el-col>
        <el-col :span="24">
          <ElFormItem label="是否启用">
            <ElSwitch :active-value="1" :inactive-value="0" v-model="formData.status" />
          </ElFormItem>
        </el-col>
        <el-col :span="24">
          <ElFormItem label="用户描述">
            <ElInput
              show-word-limit
              maxlength="100"
              type="textarea"
              :rows="4"
              resize="none"
              v-model="formData.remark"
              placeholder="请输入描述"
              clearable
            />
          </ElFormItem>
        </el-col>
      </el-row>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit" :loading="submitLoading">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import {
    fetchAddUser,
    fetchGetRoleAllList,
    // fetchGetUserById,
    fetchUpdateUser
  } from '@/api/system-manage'
  import { ROLE_LIST_DATA } from '@/mock/temp/formData'
  import type { FormInstance, FormRules } from 'element-plus'

  interface Props {
    visible: boolean
    type: string
    userData?: Partial<Api.SystemManage.User>
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 角色列表数据
  const roleList = ref(ROLE_LIST_DATA)
  const submitLoading = ref(false)

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  const dialogType = computed(() => props.type)

  // 表单实例
  const formRef = ref<FormInstance>()

  // 表单数据
  const formData = reactive({
    username: '',
    phone: '',
    roleIds: [2] as number[],
    email: '',
    remark: '',
    status: 1,
    nickname: '',
    qq: '',
    password: 'a123456'
  })

  // 表单验证规则
  const rules: FormRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: ['blur', 'change'] }]
  }

  const getRoleList = async () => {
    let res = await fetchGetRoleAllList()
    console.log('res', res)
    if (res.code === 200) {
      roleList.value = res.data.items
    } else {
      roleList.value = []
    }
  }

  /**
   * 初始化表单数据
   * 根据对话框类型（新增/编辑）填充表单
   */
  const initFormData = async () => {
    const isEdit = props.type === 'edit' && props.userData
    const row = props.userData
    // if (isEdit) {
    //   let res = await fetchGetUserById(row!.id!)
    //   console.log('根据id获取用户信息:', res)
    // }
    getRoleList()
    console.log('初始化表单数据:', row?.status)
    Object.assign(formData, {
      username: isEdit && row ? row.username || '' : '',
      phone: isEdit && row ? row.phone || '' : '',
      email: isEdit && row ? row.email || '' : '',
      nickname: isEdit && row ? row.nickname || '' : '',
      qq: isEdit && row ? row.qq || '' : '',
      remark: isEdit && row ? row.remark || '' : '',
      status: isEdit && row ? row.status : 1,
      password: isEdit && row ? row.psalt : 'a123456',
      roleIds: isEdit && row ? (Array.isArray(row.roles) ? row.roles.map((v) => v.id) : []) : [2]
    })
  }

  /**
   * 监听对话框状态变化
   * 当对话框打开时初始化表单数据并清除验证状态
   */
  watch(
    () => [props.visible, props.type, props.userData],
    ([visible]) => {
      if (visible) {
        initFormData()
        nextTick(() => {
          formRef.value?.clearValidate()
        })
      }
    },
    { immediate: true }
  )

  /**
   * 提交表单
   * 验证通过后触发提交事件
   */
  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (valid) {
        submitLoading.value = true
        const isEdit = props.type === 'edit' && props.userData
        console.log('提交的表单数据:', formData)
        let dataParams = isEdit ? { ...formData, id: props.userData?.id } : { ...formData }
        let res
        if (isEdit) {
          const { password, ...payload } = dataParams
          console.log('编辑用户, payload:', password)
          res = await fetchUpdateUser(props.userData!.id as number, payload)
        } else {
          res = await fetchAddUser(dataParams)
        }
        if (res.code === 200) {
          ElMessage.success('操作成功')
          dialogVisible.value = false
          emit('submit')
        }
        submitLoading.value = false
      }
    })
  }
</script>
